/*    Copyright 2010 Tobias Marschall
 *
 *    This file is part of MoSDi.
 *
 *    MoSDi is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    MoSDi is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with MoSDi.  If not, see <http://www.gnu.org/licenses/>.
 */

package mosdi.discovery;

import java.util.ArrayList;
import java.util.List;

import mosdi.discovery.MotifFinder.SearchState;
import mosdi.util.BitArray;

/** Searches for all patterns that occur in more sequences than specified by
 *  a threshold. */
public class SequenceCountThresholdSearch implements MotifFinder.SearchSpecification {
	private BitArray[] sequenceOccurrenceAnnotation;
	private int sequenceCount;
	private int threshold;
	private List<EvaluatedPattern> results;
	private SearchState state;
	
	public SequenceCountThresholdSearch(int threshold, BitArray[] sequenceOccurrenceAnnotation) {
		this.sequenceOccurrenceAnnotation = sequenceOccurrenceAnnotation;
		this.threshold = threshold;
		this.sequenceCount = sequenceOccurrenceAnnotation[0].size();
	}
	
	@Override
	public void initialize(SearchState searchState) {
		results = new ArrayList<EvaluatedPattern>();
		this.state = searchState;
	}
	
	@Override
	public void updatePattern(int newCharacter, int leftmostChangedPosition) { }

	@Override
	public boolean check(int prefixLength, int[] nodes) {
		return getScore(nodes)>=threshold;
	}
	
	@Override
	public void evaluateCandidate(int[] nodes) {
		int score = getScore(nodes);
		if (score>=threshold) results.add(new EvaluatedPattern(state.getPattern(), score));
	}

	public int getScore(int[] nodes) {
		BitArray ba = new BitArray(sequenceCount);
		for (int node : nodes) ba.or(sequenceOccurrenceAnnotation[node]);
		return ba.numberOfOnes();
	}
	
	public List<EvaluatedPattern> getResults() { return results; }
}
